import { defineStore } from 'pinia'
import { login, logout, getUserInfo } from '@/api/user.js'
import { message } from 'ant-design-vue'
export const useUserStore = defineStore('user', {
  state() {
    return {
      token: '',
      userInfo: null,
      routers: []
    }
  },
  getters: {
    getToken: (state) => {
      return state.token
    },
    getUser: (state) => {
      return state.userInfo
    }
  },
  actions: {
    setToken(info) {
      this.token = info
    },
    setUserInfo(info) {
      this.userInfo = info
    },
    async Login(userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(res => {
          if(res.code === 500) return
          this.setToken(res.data.token)
          this.getUserInfoList()
          resolve()
        })
      })
    },
    async logout() {
      return new Promise((resolve, reject) => {
        logout().then((res) => {
          this.setToken('')
          sessionStorage.clear()
          message.info('退出成功！')
          setTimeout(() => {
            location.reload()
          }, 1000)
          resolve(res)
        })
      })
    },
    async getUserInfoList() {
      getUserInfo().then(res => {
        this.setUserInfo(res.data)
      })
    }
  },
  persist: {
    enabled: true
  }
})